import logging
import os
import time
import unittest

from common import init_logging
from package import HTMLTestRunner
from settings import report_dir, case_dir, log_dir

init_logging()
logger = logging.getLogger(__name__)


def auto_clear(path, backup=5):
    """auto clear resource

    :param path:
    :param backup:
    :return:
    """
    filelist = []
    for file in os.listdir(path):
        filelist.append(os.path.join(path, file))

    filelist.sort(key=os.path.getctime, reverse=True)
    for file in filelist[backup:]:
        os.remove(file)


def main():
    """Program main entry

    :return:
    """
    logger.info(
        r"""
        _    _         _      _____         _   
  _   _(_)  / \  _   _| |_ __|_   _|__  ___| |_ 
 | | | | | / _ \| | | | __/ _ \| |/ _ \/ __| __|
 | |_| | |/ ___ \ |_| | || (_) | |  __/\__ \ |_ 
  \__,_|_/_/   \_\__,_|\__\___/|_|\___||___/\__|
  Starting      ...     ...     ...     ...     
    """
    )

    report_dir.mkdir(exist_ok=True)
    report_name = time.strftime('%Y-%m-%d %H-%M-%S')
    fp = open(report_dir / f'{report_name}.html', 'wb')
    runner = HTMLTestRunner.HTMLTestReport(
        stream=fp,
        verbosity=2,
        title='FecMall项目UI自动化测试报告',
        images=True
    )
    suite = unittest.TestLoader().discover(case_dir)
    runner.run(suite)
    fp.close()

    auto_clear(log_dir)
    auto_clear(report_dir)


if __name__ == '__main__':
    main()
